// DOM manipulation examples for portfolio website

// Wait for DOM to be fully loaded
document.addEventListener('DOMContentLoaded', function() {
    
    // Smooth scrolling for navigation links
    const navLinks = document.querySelectorAll('nav a[href^="#"]');
    
    navLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            
            const targetId = this.getAttribute('href');
            const targetSection = document.querySelector(targetId);
            
            if (targetSection) {
                targetSection.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
            }
        });
    });

    // Form submission handling
    const contactForm = document.getElementById('contactForm');
    
    if (contactForm) {
        contactForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // Get form data
            const formData = new FormData(this);
            const name = formData.get('name');
            const email = formData.get('email');
            const message = formData.get('message');
            
            // Get current language
            const currentLang = document.documentElement.lang || 'zh-CN';
            
            // Basic validation
            if (name && email && message) {
                // Create success message
                const successMessage = document.createElement('div');
                successMessage.className = 'success-message';
                successMessage.textContent = currentLang === 'en' ? 
                    'Message sent successfully! I will reply to you as soon as possible.' : 
                    '留言发送成功！我会尽快回复您。';
                
                // 根据当前主题设置样式
                const isLightTheme = document.body.classList.contains('light-theme');
                if (isLightTheme) {
                    successMessage.style.cssText = `
                        background-color: rgba(40, 167, 69, 0.1);
                        color: #155724;
                        padding: 1rem;
                        border-radius: 10px;
                        margin-bottom: 1rem;
                        border: 1px solid rgba(40, 167, 69, 0.3);
                        backdrop-filter: blur(10px);
                        -webkit-backdrop-filter: blur(10px);
                    `;
                } else {
                    successMessage.style.cssText = `
                        background-color: rgba(40, 167, 69, 0.2);
                        color: #a3cfbb;
                        padding: 1rem;
                        border-radius: 10px;
                        margin-bottom: 1rem;
                        border: 1px solid rgba(40, 167, 69, 0.3);
                        backdrop-filter: blur(10px);
                        -webkit-backdrop-filter: blur(10px);
                    `;
                }
                
                // Insert success message before form
                this.parentNode.insertBefore(successMessage, this);
                
                // Reset form
                this.reset();
                
                // Remove success message after 5 seconds
                setTimeout(() => {
                    successMessage.remove();
                }, 5000);
            } else {
                // Create error message
                const errorMessage = document.createElement('div');
                errorMessage.className = 'error-message';
                errorMessage.textContent = currentLang === 'en' ? 
                    'Please fill in all required fields.' : 
                    '请填写所有必填字段。';
                
                // 根据当前主题设置样式
                const isLightTheme = document.body.classList.contains('light-theme');
                if (isLightTheme) {
                    errorMessage.style.cssText = `
                        background-color: rgba(220, 53, 69, 0.1);
                        color: #721c24;
                        padding: 1rem;
                        border-radius: 10px;
                        margin-bottom: 1rem;
                        border: 1px solid rgba(220, 53, 69, 0.3);
                        backdrop-filter: blur(10px);
                        -webkit-backdrop-filter: blur(10px);
                    `;
                } else {
                    errorMessage.style.cssText = `
                        background-color: rgba(220, 53, 69, 0.2);
                        color: #f1aeb5;
                        padding: 1rem;
                        border-radius: 10px;
                        margin-bottom: 1rem;
                        border: 1px solid rgba(220, 53, 69, 0.3);
                        backdrop-filter: blur(10px);
                        -webkit-backdrop-filter: blur(10px);
                    `;
                }
                
                // Insert error message before form
                this.parentNode.insertBefore(errorMessage, this);
                
                // Remove error message after 5 seconds
                setTimeout(() => {
                    errorMessage.remove();
                }, 5000);
            }
        });
    }

    // Skill bar animation on scroll
    const skillBars = document.querySelectorAll('.skill-level');
    
    function animateSkillBars() {
        skillBars.forEach(bar => {
            const rect = bar.getBoundingClientRect();
            const isVisible = rect.top < window.innerHeight && rect.bottom > 0;
            
            if (isVisible && !bar.classList.contains('animated')) {
                bar.classList.add('animated');
                const level = bar.getAttribute('data-level');
                setTimeout(() => {
                    bar.style.width = level;
                }, 200);
            }
        });
    }

    // Initial check for skill bars
    animateSkillBars();

    // Add scroll event listener for skill bar animation
    window.addEventListener('scroll', animateSkillBars);

    // Project card hover effects
    const projectCards = document.querySelectorAll('.project-card');
    
    projectCards.forEach(card => {
        card.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-10px) scale(1.02)';
        });
        
        card.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0) scale(1)';
        });
    });

    // Mobile menu toggle (for responsive design)
    const nav = document.querySelector('nav ul');
    const menuButton = document.createElement('button');
    menuButton.className = 'mobile-menu-toggle';
    menuButton.innerHTML = '☰';
    
    // 根据当前主题设置样式
    function updateMenuButtonStyle() {
        const isLightTheme = document.body.classList.contains('light-theme');
        if (isLightTheme) {
            menuButton.style.cssText = `
                display: none;
                background: none;
                border: none;
                color: #333333;
                font-size: 1.5rem;
                cursor: pointer;
                padding: 0.5rem;
            `;
        } else {
            menuButton.style.cssText = `
                display: none;
                background: none;
                border: none;
                color: white;
                font-size: 1.5rem;
                cursor: pointer;
                padding: 0.5rem;
            `;
        }
    }
    
    // 初始化菜单按钮样式
    updateMenuButtonStyle();
    
    // Insert menu button before nav
    const navContainer = document.querySelector('nav');
    if (navContainer) {
        navContainer.insertBefore(menuButton, nav);
    }
    
    // Toggle mobile menu
    menuButton.addEventListener('click', function() {
        nav.style.display = nav.style.display === 'flex' ? 'none' : 'flex';
        nav.style.flexDirection = 'column';
        nav.style.position = 'absolute';
        nav.style.top = '100%';
        nav.style.left = '0';
        nav.style.right = '0';
        nav.style.backgroundColor = 'rgba(102, 126, 234, 0.95)';
        nav.style.padding = '1rem';
        nav.style.zIndex = '1000';
    });

    // Show/hide mobile menu based on screen size
    function handleMobileMenu() {
        if (window.innerWidth <= 768) {
            menuButton.style.display = 'block';
            nav.style.display = 'none';
        } else {
            menuButton.style.display = 'none';
            nav.style.display = 'flex';
            nav.style.position = 'static';
            nav.style.flexDirection = 'row';
            nav.style.backgroundColor = 'transparent';
            nav.style.padding = '0';
        }
    }

    // Initial check
    handleMobileMenu();
    
    // Add resize event listener
    window.addEventListener('resize', handleMobileMenu);
    
    // 监听主题变化，更新菜单按钮样式
    document.addEventListener('themeChanged', function(e) {
        updateMenuButtonStyle();
    });

    // Dynamic year for footer copyright
    const currentYear = new Date().getFullYear();
    const copyrightElement = document.querySelector('footer p');
    if (copyrightElement) {
        copyrightElement.textContent = `© ${currentYear} 个人作品集. 保留所有权利.`;
    }

    // Add loading animation
    window.addEventListener('load', function() {
        document.body.style.opacity = '0';
        document.body.style.transition = 'opacity 0.5s ease-in-out';
        
        setTimeout(() => {
            document.body.style.opacity = '1';
        }, 100);
    });

    // Intersection Observer for fade-in animations
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };

    const observer = new IntersectionObserver(function(entries) {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.style.opacity = '1';
                entry.target.style.transform = 'translateY(0)';
            }
        });
    }, observerOptions);

    // Observe all sections for fade-in effect
    const sections = document.querySelectorAll('section');
    sections.forEach(section => {
        section.style.opacity = '0';
        section.style.transform = 'translateY(30px)';
        section.style.transition = 'opacity 0.6s ease-out, transform 0.6s ease-out';
        observer.observe(section);
    });

    // Add click event to social links
    const socialLinks = document.querySelectorAll('.social-links a');
    socialLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const platform = this.getAttribute('aria-label');
            console.log(`Social link clicked: ${platform}`);
            // Here you can add actual social media linking logic
        });
    });

    // Project link click handling
    const projectLinks = document.querySelectorAll('.project-link');
    projectLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const projectTitle = this.closest('.project-card').querySelector('h3').textContent;
            console.log(`Project clicked: ${projectTitle}`);
            // Here you can add project detail page navigation logic
        });
    });
});

// Utility functions
const portfolioUtils = {
    // Format date
    formatDate: function(date) {
        return new Date(date).toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: 'long',
            day: 'numeric'
        });
    },

    // Validate email
    validateEmail: function(email) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return emailRegex.test(email);
    },

    // Copy to clipboard
    copyToClipboard: function(text) {
        navigator.clipboard.writeText(text).then(() => {
            console.log('Text copied to clipboard');
        }).catch(err => {
            console.error('Failed to copy text: ', err);
        });
    }
};

// Export for potential module usage
if (typeof module !== 'undefined' && module.exports) {
    module.exports = portfolioUtils;
}
